package view;

import java.rmi.RemoteException;
import java.util.Date;

import javax.swing.JFrame;
import javax.swing.JTable;

import controller.FirewallSession;
import server.FirewallException;
import server.GlobalLog;

/**
 * Class is responsible for global logger table.
 * Table size, column names are defined.
 */
public class LoggerGlobalTable extends AbstractLoggerTable
{	
	/**
	 * Serial version ID - for serialization
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * server controller
	 */
	public FirewallSession UI;
	
	/**
	 * Current logger table
	 */
	public static LoggerGlobalTable currentLoggerGlobalTable = null;
	
	/**
	 * Column names
	 */
	private final static String columnNames[] = 
		{"Time", "Event" };
		
	/**
	 * C'tor - Table with specified controller and size is created.
	 * Fill the table with the global logger information.
	 * @param ui	- the controller for the system actions
	 */
	public LoggerGlobalTable(FirewallSession ui)
	{
		super(Settings.windowDepth, columnNames.length);
		this.UI = ui;
		currentLoggerGlobalTable = this;
		  
	    setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
	    currentLoggerGlobalTable.getColumnModel().getColumn(0).setPreferredWidth(200);
	    currentLoggerGlobalTable.getColumnModel().getColumn(1).setPreferredWidth(600);
	    buildTable();
	}

	/** 
	 * @return the names of the table columns
	 */
	public String[] getColumnNames()
	{
		return columnNames;
	}
	
	/**
	 * Fill the table with logger data.
	 * @param objectData - the logger data to put to the table
	 */
	public void fillTable(Object[] loggerData)
	{
		GlobalLog[] loggerGlobalData = (GlobalLog[])loggerData;
		
		/* Fill the data in table from received */
		int j = 0;
		for(int i = 0; i < loggerGlobalData.length; i++)
		{
			/* Check if data is valid */
			if(loggerGlobalData[i] != null)
			{
				j = 0;
				this.setValueAt(new Date(loggerGlobalData[i].time * Globals.MSEC),  i, j++);
				this.setValueAt(loggerGlobalData[i].event, i, j++);					
			}
			else /* Data isn't valid - read the next row */
			{
				/* N/A */
				continue;
			}
		}
	}
	
	/**
	 * Get the global logger data from UI.
	 * @return the logger data in array
	 */
	protected Object[] getLoggerData()
	{
		try {
			return UI.getGlobalLogs( Settings.historyDepth);			
		} catch (RemoteException e) {
			ErrorFrame.AddError("Failed to get log data:" + e.getMessage(), new JFrame());
		} catch (FirewallException e) {
			ErrorFrame.AddError("Failed to get log data:"  + e.getMessage(), new JFrame());
		}
		
		return null;
	}

	/**
	 * Get the table name.
	 * @return the logger table name
	 */
	protected String getTableName()
	{
		return "Global Logger";
	}
}
